﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.eCardReport.DBDao;
using Customer_Profile.Admin;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Customer_Profile.CRM
{
    public partial class SimpleSMS : System.Web.UI.Page
    {
        string strUserName = "";
        string strUserID = "";
        string strEntity = "";
        public string strScript = "";
        DataSet dsResult = null;
        string sms_userid = KVB.Common.Configuration.GetKeyValue("SMS", "userid");
        string sms_password = KVB.Common.Configuration.GetKeyValue("SMS", "password");
        string sms_url = KVB.Common.Configuration.GetKeyValue("SMS", "URL");
        int sms_size = Convert.ToInt32(KVB.Common.Configuration.GetKeyValue("SMS", "size"));

        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }

            DataSet dsProd = ProductDao.getAllProduct("ALL");
            DevExpress.Web.ASPxEditors.ASPxListBox listbox = (DevExpress.Web.ASPxEditors.ASPxListBox)ASPxDropDownEdit1.FindControl("listBox");
            listbox.DataSource = dsProd;
            listbox.TextField = "procduct_name";
            listbox.ValueField = "procduct_code";
            listbox.DataBind();

            DevExpress.Web.ASPxEditors.ListEditItem li = new DevExpress.Web.ASPxEditors.ListEditItem("选择全部");
            listbox.Items.Insert(0, li);  

            //this.txtSumAmount.Attributes.Add("readonly", "readonly");
            if (!Page.IsPostBack)
            {
                DataSet dsEntity = EntityDao.getEntityList("N");
                dropEntity.DataSource = dsEntity;
                dropEntity.DataTextField = "entity_name";
                dropEntity.DataValueField = "entity_id";
                dropEntity.DataBind();
                ListItem liAllEntity = new ListItem();
                liAllEntity.Text = "All";
                liAllEntity.Value = "All";
                dropEntity.Items.Insert(0, liAllEntity);

                Comm.BindDll(ref dropCpartyCatalog, "SMSCpartyType", true, "");
            }
            bindGrid();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            //Server.UrlEncode           
        }

        private void bindGrid()
        {
            try
            {
                string strSQL = "SELECT DISTINCT md.cparty_id,cp.cparty_name,cp.phone,cp.id_type,cp.id_no,md.entity,cp.address FROM dbo.mmdeals md INNER JOIN dbo.cparty cp ON md.cparty_id = cp.cparty_id WHERE if_returncard='N' AND LEN(phone)=11 AND SUBSTRING(phone,1,1)='1' ";
                string strTempSQL = "SELECT cparty_id FROM dbo.mmdeals WHERE if_returncard='N' ";

                if (txtcreatedatebegin.Text.Trim() != "" && txtcreatedateend.Text.Trim() != "")
                {
                    strSQL += " AND CONVERT(DATE,value_date) BETWEEN '" + txtcreatedatebegin.Text.Trim() + "' AND '" + txtcreatedateend.Text.Trim() + "' ";
                    strTempSQL += " AND CONVERT(DATE,value_date) BETWEEN '" + txtcreatedatebegin.Text.Trim() + "' AND '" + txtcreatedateend.Text.Trim() + "' ";
                }

                if (due_date_start.Text.Trim() != "" && due_date_end.Text.Trim() != "")
                {
                    strSQL += " AND CONVERT(DATE,due_date) BETWEEN '" + due_date_start.Text.Trim() + "' AND '" + due_date_end.Text.Trim() + "' ";
                    strTempSQL += " AND CONVERT(DATE,due_date) BETWEEN '" + due_date_start.Text.Trim() + "' AND '" + due_date_end.Text.Trim() + "' ";
                }

                if (amount_start.Text.Trim() != "" && amount_end.Text.Trim() != "")
                {
                    strSQL += " AND initial_amount BETWEEN '" + amount_start.Text.Trim() + "' AND '" + amount_end.Text.Trim() + "' ";
                    strTempSQL += " AND initial_amount BETWEEN '" + amount_start.Text.Trim() + "' AND '" + amount_end.Text.Trim() + "' ";
                }

                if (dropEntity.SelectedIndex > 0)
                {
                    strSQL += " AND md.entity_id = '" + dropEntity.SelectedItem.Value.Trim() + "' ";
                    strTempSQL += " AND entity_id = '" + dropEntity.SelectedItem.Value.Trim() + "' ";
                }

                if (!ASPxDropDownEdit1.Text.Trim().Equals(""))
                {
                    strSQL += " AND prod_code in (select STR1 from dbo.fn_SPLITSTR('" + ASPxDropDownEdit1.Text.Trim() + "',';')) ";
                }

                if (dropCpartyCatalog.SelectedIndex == 2)
                {
                    strSQL += " AND CONVERT(DATE,due_date) BETWEEN CONVERT(VARCHAR(10),GETDATE(),120) AND  CONVERT(VARCHAR(10),DATEADD(Year,1,GETDATE()),120) ";
                }

                if (dropCpartyCatalog.SelectedIndex == 1)
                {
                    strSQL += " AND md.cparty_id NOT IN ( " + strTempSQL + "  AND CONVERT(DATE,due_date) BETWEEN CONVERT(VARCHAR(10),GETDATE(),120) AND  CONVERT(VARCHAR(10),DATEADD(Year,1,GETDATE()),120)) ";
                }
                if (dropCpartyCatalog.SelectedIndex == 3)
                {
                    strSQL += " AND CONVERT(DATE,due_date) BETWEEN CONVERT(VARCHAR(10),GETDATE(),120) AND  CONVERT(VARCHAR(10),DATEADD(Year,1,GETDATE()),120) AND md.cparty_id in (" + strTempSQL + " AND CONVERT(DATE,due_date) BETWEEN '1900-01-01' AND CONVERT(VARCHAR(10),GETDATE(),120) )";
                }

                //Log.WriteDefaultLog("SQL:", strSQL);
                dsResult = ReportDao.DairySumReport(strSQL);
                gridReward.DataSource = dsResult;
                gridReward.DataBind();
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("SimpleSMS:",ex.ToString());
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {           
           if (dsResult != null && dsResult.Tables[0].Rows.Count > 0)
            {
                SqlConnection conn = null;
                DB.Connection(ref conn);
                SqlTransaction trans = conn.BeginTransaction();
                SqlCommand sqlCommand = new SqlCommand();
                sqlCommand.Connection = conn;
                sqlCommand.Transaction = trans;

                try
                {                 
                    //添加SMS主表信息
                    sqlCommand.Parameters.Clear();
                    string title = txtTitle.Text.Trim();
                    string content = txtContent.Text.Trim();
                    int sms_id ;
                    
                    sqlCommand.Parameters.Add("@sms_title", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_content", SqlDbType.VarChar, 8000);
                    sqlCommand.Parameters.Add("@input_userid", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@input_username", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);                    

                    sqlCommand.Parameters["@sms_title"].Value = title;
                    sqlCommand.Parameters["@sms_content"].Value = content;
                    sqlCommand.Parameters["@input_userid"].Value = strUserID;
                    sqlCommand.Parameters["@input_username"].Value = strUserName;
                    sqlCommand.Parameters["@sms_id"].Direction = ParameterDirection.Output;

                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.CommandText = "eCard_SMS_Insert";
                    sqlCommand.ExecuteNonQuery();

                    sms_id = Convert.ToInt32( sqlCommand.Parameters["@sms_id"].Value.ToString());

                    int iGroup = dsResult.Tables[0].Rows.Count / sms_size;
                    for (int i = 0; i <= iGroup; i++)
                    {
                        string target = "";
                        for (int j = 0; j < sms_size; j++)
                        {
                            if (sms_size * i + j < dsResult.Tables[0].Rows.Count)
                                target += dsResult.Tables[0].Rows[sms_size * i + j]["phone"].ToString().Trim() + ";";
                            else
                                break;
                        }

                        //添加SMS主表对应的电话号码信息。                        
                        sqlCommand.Parameters.Clear();                        
                        
                        sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);
                        sqlCommand.Parameters.Add("@sms_phoneno", SqlDbType.VarChar, 8000);

                        sqlCommand.Parameters["@sms_id"].Value = sms_id;
                        sqlCommand.Parameters["@sms_phoneno"].Value = target;                        

                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.CommandText = "eCard_SMS_PhoneNO";
                        sqlCommand.ExecuteNonQuery();
                       
                    }
                    trans.Commit();
                    strScript = "<script language='javascript' >alert('上传成功，请等待发送完毕。')</script>";
                }
                catch (Exception ex)
                {
                    KVB.Common.Log.WriteDefaultLog("SimpleSMS.btnSubmit_Click", ex.ToString());
                    trans.Rollback();                    
                    strScript = "<script language='javascript' >alert('请联系管理员！上传短信数据失败！'+" + ex.ToString() + ")</script>";
                }
                finally
                {
                    DB.ConnDispose(ref conn);
                    trans.Dispose();
                    conn.Dispose();
                }
            }
        }

        protected void btnSubmitCheck_Click(object sender, EventArgs e)
        {
            if (hidDealno.Value!="")
            {
                SqlConnection conn = null;
                DB.Connection(ref conn);
                SqlTransaction trans = conn.BeginTransaction();
                SqlCommand sqlCommand = new SqlCommand();
                sqlCommand.Connection = conn;
                sqlCommand.Transaction = trans;

                try
                {
                    //添加SMS主表信息
                    sqlCommand.Parameters.Clear();
                    string title = txtTitle.Text.Trim();
                    string content = txtContent.Text.Trim();
                    int sms_id;

                    sqlCommand.Parameters.Add("@sms_title", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_content", SqlDbType.VarChar, 8000);
                    sqlCommand.Parameters.Add("@input_userid", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@input_username", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);

                    sqlCommand.Parameters["@sms_title"].Value = title;
                    sqlCommand.Parameters["@sms_content"].Value = content;
                    sqlCommand.Parameters["@input_userid"].Value = strUserID;
                    sqlCommand.Parameters["@input_username"].Value = strUserName;
                    sqlCommand.Parameters["@sms_id"].Direction = ParameterDirection.Output;

                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.CommandText = "eCard_SMS_Insert";
                    sqlCommand.ExecuteNonQuery();

                    sms_id = Convert.ToInt32(sqlCommand.Parameters["@sms_id"].Value.ToString());

                    string[] phoneno_list = hidDealno.Value.Substring(0,hidDealno.Value.Length-1).Split(',');
                    int iGroup = phoneno_list.Length / sms_size;
                    for (int i = 0; i <= iGroup; i++)
                    {
                        string target = "";
                        for (int j = 0; j < sms_size; j++)
                        {
                            if (sms_size * i + j < phoneno_list.Length)
                                target += phoneno_list[sms_size * i + j].ToString().Trim() + ";";
                            else
                                break;
                        }

                        //添加SMS主表对应的电话号码信息。                        
                        sqlCommand.Parameters.Clear();

                        sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);
                        sqlCommand.Parameters.Add("@sms_phoneno", SqlDbType.VarChar, 8000);

                        sqlCommand.Parameters["@sms_id"].Value = sms_id;
                        sqlCommand.Parameters["@sms_phoneno"].Value = target;

                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.CommandText = "eCard_SMS_PhoneNO";
                        sqlCommand.ExecuteNonQuery();

                    }
                    trans.Commit();
                    strScript = "<script language='javascript' >alert('上传成功，请等待发送完毕。')</script>";
                }
                catch (Exception ex)
                {
                    KVB.Common.Log.WriteDefaultLog("SimpleSMS.btnSubmit_Click", ex.ToString());
                    trans.Rollback();
                    strScript = "<script language='javascript' >alert('请联系管理员！上传短信数据失败！'+" + ex.ToString() + ")</script>";
                }
                finally
                {
                    DB.ConnDispose(ref conn);
                    trans.Dispose();
                    conn.Dispose();
                }
            }
        }

        protected void btnSubmitSpecial_Click(object sender, EventArgs e)
        {
            if (txtPhoneno.Text.Trim() != "")
            {
                SqlConnection conn = null;
                DB.Connection(ref conn);
                SqlTransaction trans = conn.BeginTransaction();
                SqlCommand sqlCommand = new SqlCommand();
                sqlCommand.Connection = conn;
                sqlCommand.Transaction = trans;

                try
                {
                    //添加SMS主表信息
                    sqlCommand.Parameters.Clear();
                    string title = txtTitle.Text.Trim();
                    string content = txtContent.Text.Trim();
                    int sms_id;

                    sqlCommand.Parameters.Add("@sms_title", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_content", SqlDbType.VarChar, 8000);
                    sqlCommand.Parameters.Add("@input_userid", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@input_username", SqlDbType.VarChar, 250);
                    sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);

                    sqlCommand.Parameters["@sms_title"].Value = title;
                    sqlCommand.Parameters["@sms_content"].Value = content;
                    sqlCommand.Parameters["@input_userid"].Value = strUserID;
                    sqlCommand.Parameters["@input_username"].Value = strUserName;
                    sqlCommand.Parameters["@sms_id"].Direction = ParameterDirection.Output;

                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.CommandText = "eCard_SMS_Insert";
                    sqlCommand.ExecuteNonQuery();

                    sms_id = Convert.ToInt32(sqlCommand.Parameters["@sms_id"].Value.ToString());

                    string[] phoneno_list = txtPhoneno.Text.Split(';');
                    int iGroup = phoneno_list.Length / sms_size;
                    for (int i = 0; i <= iGroup; i++)
                    {
                        string target = "";
                        for (int j = 0; j < sms_size; j++)
                        {
                            if (sms_size * i + j < phoneno_list.Length)
                                target += phoneno_list[sms_size * i + j].ToString().Trim() + ";";
                            else
                                break;
                        }

                        //添加SMS主表对应的电话号码信息。                        
                        sqlCommand.Parameters.Clear();

                        sqlCommand.Parameters.Add("@sms_id", SqlDbType.Int);
                        sqlCommand.Parameters.Add("@sms_phoneno", SqlDbType.VarChar, 8000);

                        sqlCommand.Parameters["@sms_id"].Value = sms_id;
                        sqlCommand.Parameters["@sms_phoneno"].Value = target;

                        sqlCommand.CommandType = CommandType.StoredProcedure;
                        sqlCommand.CommandText = "eCard_SMS_PhoneNO";
                        sqlCommand.ExecuteNonQuery();

                    }
                    trans.Commit();
                    strScript = "<script language='javascript' >alert('上传成功，请等待发送完毕。')</script>";
                }
                catch (Exception ex)
                {
                    KVB.Common.Log.WriteDefaultLog("SimpleSMS.btnSubmit_Click", ex.ToString());
                    trans.Rollback();
                    strScript = "<script language='javascript' >alert('请联系管理员！上传短信数据失败！'+" + ex.ToString() + ")</script>";
                }
                finally
                {
                    DB.ConnDispose(ref conn);
                    trans.Dispose();
                    conn.Dispose();
                }
            }
        }
    }
}